<template>
  <div class="workflow-save-reuse">
    <!-- Part 1: Save Button -->
    <el-button v-if="componentType === 'save-button'" @click="openSaveDialog">保存</el-button>

    <!-- Part 2: Template/History List -->
    <div v-if="componentType.includes('list')">
      <el-input v-model="searchTerm" placeholder="搜索..." clearable class="search-input"/>
      <el-table :data="filteredList" height="calc(100vh - 250px)" @row-click="loadWorkflow">
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="savedAt" label="保存时间" width="160"></el-table-column>
        <el-table-column label="操作" width="80">
            <template #default="scope">
                <el-button type="danger" size="small" @click.stop="deleteWorkflow(scope.row.id)">删除</el-button>
            </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Save Dialog -->
    <CommonModal :visible="saveDialogVisible" title="保存工作流" @close="saveDialogVisible = false" @confirm="handleSave">
      <el-form :model="saveForm" :rules="rules" ref="saveFormRef" label-width="100px">
        <el-form-item label="工作流名称" prop="name">
          <el-input v-model="saveForm.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="saveForm.description" type="textarea" :rows="3" placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-form-item label="设为模板" prop="isTemplate">
          <el-switch v-model="saveForm.isTemplate"></el-switch>
        </el-form-item>
      </el-form>
    </CommonModal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useWorkflowStore } from '../../stores/workflow';
import { ElMessage, ElMessageBox } from 'element-plus';
import CommonModal from '../common/CommonModal.vue';

const props = defineProps({
  componentType: {
    type: String,
    required: true, // 'save-button', 'template-list', 'history-list'
  },
});

const MOCK_STORAGE_KEY = 'immune_workflows';

const workflowStore = useWorkflowStore();
const saveDialogVisible = ref(false);
const saveFormRef = ref(null);
const saveForm = ref({
  name: '',
  description: '',
  isTemplate: false,
});
const rules = {
  name: [{ required: true, message: '请输入工作流名称', trigger: 'blur' }],
};

const allWorkflows = ref([]);
const searchTerm = ref('');

onMounted(() => {
  if (props.componentType.includes('list')) {
    loadAllWorkflows();
  }
});

const filteredList = computed(() => {
  const isTemplateList = props.componentType === 'template-list';
  return allWorkflows.value.filter(w => {
    const typeMatch = isTemplateList ? w.isTemplate : !w.isTemplate;
    const searchMatch = searchTerm.value ? w.name.includes(searchTerm.value) : true;
    return typeMatch && searchMatch;
  }).sort((a, b) => new Date(b.savedAt) - new Date(a.savedAt));
});

const loadAllWorkflows = () => {
  const data = localStorage.getItem(MOCK_STORAGE_KEY);
  allWorkflows.value = data ? JSON.parse(data) : [];
};

const openSaveDialog = () => {
  if (!workflowStore.workflowData || workflowStore.workflowData.nodeDataArray.length === 0) {
    ElMessage.warning('画布为空，无法保存');
    return;
  }
  saveForm.value = { name: '', description: '', isTemplate: false };
  saveDialogVisible.value = true;
};

const handleSave = async () => {
  if (!saveFormRef.value) return;
  await saveFormRef.value.validate((valid) => {
    if (valid) {
      loadAllWorkflows();
      const newWorkflow = {
        id: Date.now(),
        name: saveForm.value.name,
        description: saveForm.value.description,
        isTemplate: saveForm.value.isTemplate,
        savedAt: new Date().toLocaleString(),
        data: workflowStore.workflowData,
      };
      allWorkflows.value.push(newWorkflow);
      localStorage.setItem(MOCK_STORAGE_KEY, JSON.stringify(allWorkflows.value));
      ElMessage.success('保存成功');
      saveDialogVisible.value = false;
    }
  });
};

const loadWorkflow = (workflow) => {
    ElMessageBox.confirm(`确定要加载 "${workflow.name}" 吗？当前画布内容将被覆盖。`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        workflowStore.updateWorkflow(JSON.parse(JSON.stringify(workflow.data)));
        ElMessage.success('加载成功');
    }).catch(() => {});
};

const deleteWorkflow = (id) => {
    ElMessageBox.confirm('确定要删除此工作流吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        loadAllWorkflows();
        const updatedWorkflows = allWorkflows.value.filter(w => w.id !== id);
        localStorage.setItem(MOCK_STORAGE_KEY, JSON.stringify(updatedWorkflows));
        loadAllWorkflows(); // Refresh the list
        ElMessage.success('删除成功');
    }).catch(() => {});
};

</script>

<style scoped>
.search-input {
  margin-bottom: 10px;
}
</style>
